package com.chtw.oasystem.service.impl;

import cn.hutool.core.util.IdUtil;
import com.chtw.oasystem.bean.*;
import com.chtw.oasystem.common.changelogs.ChangeLogsUtils;
import com.chtw.oasystem.mapper.CheckingInMapper;
import com.chtw.oasystem.mapper.DeptsMapper;
import com.chtw.oasystem.mapper.UsersMapper;
import com.chtw.oasystem.respBean.CheckListResp;
import com.chtw.oasystem.respBean.UserResp;
import com.chtw.oasystem.service.UsersService;
import com.chtw.oasystem.utils.Session;
import com.chtw.oasystem.utils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author chtw
 * @date 2020-11-16 22:07
 */
@Service
public class UsersServiceImpl implements UsersService {
    private static final Logger logger = LoggerFactory.getLogger(UsersServiceImpl.class);
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private ChangeLogServiceImpl changeLogService;

    @Autowired
    private DeptsMapper deptsMapper;

    @Autowired
    private UsersServiceImpl usersService;

    @Autowired
    private DeptServiceImpl deptService;

    @Autowired
    private CheckingInMapper checkingInMapper;

    private String generateWordId() {
        String maxId = String.valueOf(usersMapper.selectMaxId() + 1000);
        return "DH" + maxId;
    }

    @Override
    public boolean createUser(HttpSession session, Users users) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser == null) {
                throw new RuntimeException("用户未登录！");
            } else if (currentUser.getRoleId() < 1) {
                ChangeLogs changeLog = ChangeLogsUtils.generateUsersChangeLog(currentUser.getUserName(), users.getUserName(), "添加");
                changeLogService.saveChangeLog(changeLog);
                DeptsExample example = new DeptsExample();
                DeptsExample.Criteria re = example.createCriteria();
                re.andDeptIdEqualTo(users.getDeptId());
                Depts leader = deptsMapper.selectByExample(example).get(0);
                users.setLeaderId(leader.getLeaderId());
                users.setUserId(IdUtil.simpleUUID());
                users.setActive(0);
                users.setWorkId(this.generateWordId());
                users.setCreated(TimeUtils.currentTimeMillis());
                users.setJoinTime(TimeUtils.getToday());
                users.setPassword("123456789");
                logger.info(users.toString());
                int inserted = usersMapper.insert(users);
                return inserted > 0;
            } else {
                throw new RuntimeException("没有权限！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public boolean editUser(HttpSession session, Users users) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser == null) {
                throw new RuntimeException("用户未登录！");
            } else if (currentUser.getRoleId() < 1) {
                ChangeLogs changeLog = ChangeLogsUtils.generateUsersChangeLog(currentUser.getUserName(), users.getUserName(), "编辑");
                changeLogService.saveChangeLog(changeLog);
                UsersExample example = new UsersExample();
                UsersExample.Criteria re = example.createCriteria();
                re.andUserIdEqualTo(users.getUserId());
                int edit = usersMapper.updateByExampleSelective(users, example);
                return edit > 0;
            } else {
                throw new RuntimeException("没有权限！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public FullUserInfo getUserByUserId(HttpSession session, String user_id) {
        try {
            CheckingInExample example = new CheckingInExample();
            CheckingInExample.Criteria re = example.createCriteria();
            String today = TimeUtils.getToday();
            int now = TimeUtils.currentTimeMillis();
            re.andCheckingDayEqualTo(today);
            if ("".equals(user_id) || user_id == null) {
                FullUserInfo currentUser = Session.getCurrentUser(session);
                if (currentUser != null) {
                    re.andUserIdEqualTo(currentUser.getUserId());
                    List<CheckingIn> checkingIns = checkingInMapper.selectByExample(example);
                    if (checkingIns.size() > 0) {
                        currentUser.setChecking_status(checkingIns.get(0).getCheckingStatus());
                    } else {
                        int h = TimeUtils.getTimestamp(TimeUtils.FULL_TIME_FORMAT, today + " 09:00:00");
                        if (h > now) {
                            currentUser.setChecking_status(3); //未打卡
                        } else {
                            currentUser.setChecking_status(2); //迟到
                        }
                    }
                    return currentUser;
                }
                throw new RuntimeException("获取当前用户信息失败");
            }
            FullUserInfo currentUser = usersMapper.selectFullUserByUserId(user_id);
            example = new CheckingInExample();
            re = example.createCriteria();
            re.andCheckingDayEqualTo(TimeUtils.getToday());
            re.andUserIdEqualTo(currentUser.getUserId());
            List<CheckingIn> checkingIns = checkingInMapper.selectByExample(example);
            if (checkingIns.size() > 0) {
                currentUser.setChecking_status(checkingIns.get(0).getCheckingStatus());
            } else {
                int h = TimeUtils.getTimestamp(TimeUtils.FULL_TIME_FORMAT, today + " 09:00:00");
                if (h > now) {
                    currentUser.setChecking_status(3); //未打卡
                } else {
                    currentUser.setChecking_status(2); //迟到
                }
            }
            return currentUser;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    @Override
    public PageInfo<FullUserInfo> list(int page, int size, String search, String dept_id) {
        try {
            PageHelper.startPage(page, size);
            List<FullUserInfo> users = usersMapper.selectFullUserInfo(search, dept_id);
            return new PageInfo<>(users);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public boolean login(HttpSession session, String work_id, String password) {
        try {
            UsersExample example = new UsersExample();
            UsersExample.Criteria criteria = example.createCriteria();
            criteria.andWorkIdEqualTo(work_id);
            criteria.andPasswordEqualTo(password);
            criteria.andActiveEqualTo(0);
            List<Users> users = usersMapper.selectByExample(example);
            if (users.size() > 0) {
                Users user = users.get(0);
                FullUserInfo fullUserInfo = usersMapper.selectFullUserByUserId(user.getUserId());
                System.out.println(fullUserInfo);
                session.setAttribute("user_info", fullUserInfo);
                session.setAttribute("user_name", user.getUserName());
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public boolean delete(HttpSession session, String userId) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser == null) {
                throw new RuntimeException("用户未登录！");
            } else if (currentUser.getRoleId() < 1) {
                Users user = new Users();
                user.setActive(2);
                UsersExample example = new UsersExample();
                UsersExample.Criteria criteria = example.createCriteria();
                criteria.andUserIdEqualTo(userId);
                int isDel = usersMapper.updateByExampleSelective(user, example);
                if (isDel > 0) {
                    ChangeLogs changeLog = ChangeLogsUtils.generateUsersChangeLog(currentUser.getUserName(), user.getUserName(), "删除");
                    changeLogService.saveChangeLog(changeLog);
                    return true;
                }
                return false;
            } else {
                throw new RuntimeException("没有权限！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public List<UserResp> all() {
        UsersExample example = new UsersExample();
        UsersExample.Criteria re = example.createCriteria();
        re.andActiveEqualTo(0);
        List<Users> users = usersMapper.selectByExample(example);
        List<UserResp> resUsers = new ArrayList<>();
        users.forEach(user -> {
            resUsers.add(new UserResp(user.getUserId(), user.getUserName(), user.getWorkId()));
        });
        return resUsers;
    }

    public List<String> getOwnerUserNames(List<String> deptIds) {
        Set<String> userNamesSet = new HashSet<>();
        for (String deptId : deptIds) {
            UsersExample example = new UsersExample();
            UsersExample.Criteria re = example.createCriteria();
            re.andDeptIdEqualTo(deptId);
            List<Users> users = usersMapper.selectByExample(example);
            for (Users user : users) {
                userNamesSet.add(user.getUserName());
            }
        }
        return new ArrayList<>(userNamesSet);
    }

    public List<Users> getOwnerUsers(List<String> deptIds) {
        Set<Users> users = new HashSet<>();
        for (String deptId : deptIds) {
            UsersExample example = new UsersExample();
            UsersExample.Criteria re = example.createCriteria();
            re.andDeptIdEqualTo(deptId);
            List<Users> us = usersMapper.selectByExample(example);
            users.addAll(us);
        }
        return new ArrayList<>(users);
    }

    public boolean check(HttpSession session) {
        try {
            FullUserInfo currentUser = Session.getCurrentUser(session);
            if (currentUser == null) {
                throw new RuntimeException("用户未登录！");
            } else {
                int now = TimeUtils.currentTimeMillis();
                String today = TimeUtils.getToday();
                int h = TimeUtils.getTimestamp(TimeUtils.FULL_TIME_FORMAT, today + " 09:00:00");
                CheckingInExample example = new CheckingInExample();
                CheckingInExample.Criteria re = example.createCriteria();
                re.andCheckingDayEqualTo(today);
                re.andUserIdEqualTo(currentUser.getUserId());
                List<CheckingIn> checkingIns = checkingInMapper.selectByExample(example);
                if (checkingIns.size() > 0) {
                    throw new RuntimeException("今日已提交打卡");
                } else {
                    CheckingIn checkingIn = new CheckingIn();
                    checkingIn.setCheckingDay(today);
                    checkingIn.setUserId(currentUser.getUserId());
                    checkingIn.setStipulateTime(today + " 09:00:00");
                    checkingIn.setCreated(now);
                    if (h > now) {
                        checkingIn.setCheckingStatus(1);
                    } else {
                        checkingIn.setCheckingStatus(4);
                    }
                    return checkingInMapper.insert(checkingIn) > 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public CheckListResp checkList(HttpSession session, int page, int limit, String checkingDay) {
        FullUserInfo currentUser = Session.getCurrentUser(session);

        if (currentUser != null) {
            String deptId = currentUser.getDeptId();
            List<String> ownerDeptIds = deptService.getOwnerDeptIds(deptId);
            List<Users> OwnerUsers = usersService.getOwnerUsers(ownerDeptIds);
            Users u = new Users();
            u.setUserId(currentUser.getUserId());
            u.setUserName(currentUser.getUserName());
            OwnerUsers.add(u);
            List<String> userIds = new ArrayList<>();
            for (Users user : OwnerUsers) {
                userIds.add(user.getUserId());
            }
            PageHelper.startPage(page, limit);
            CheckingInExample example = new CheckingInExample();
            CheckingInExample.Criteria re = example.createCriteria();
            re.andUserIdIn(userIds);
            if (checkingDay != null) re.andCheckingDayEqualTo(checkingDay);
            List<CheckingIn> is = checkingInMapper.selectByExample(example);
            PageInfo<CheckingIn> info = new PageInfo<>(is);
            CheckListResp resp = new CheckListResp();
            resp.setTotal((int) info.getTotal());
            resp.setPage_total(info.getPages());
            for (int i = 0; i < is.size(); i++) {
                for (Users user : OwnerUsers) {
                    if (is.get(i).getUserId().equals(user.getUserId())) {
                        is.get(i).setUserName(user.getUserName());
                        break;
                    }
                }
            }
            resp.setCheckingIns(is);
            return resp;
        }
        throw new RuntimeException("用户未登录！");
    }
}
